<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserChannels;
use plugin\ycMassage\app\model\MassageUserChannelsBill;
use plugin\ycMassage\app\model\MassageUserChannelsCategory;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\MoneyAction;
use plugin\ycMassage\utils\enum\NoticeType;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\notice\Notice;
use support\Request;
use think\facade\Db;

class ChannelsController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/Channels/examine',
            'path' => '/Channels/examine',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => 0
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('edit', '编辑', [
            'api'    => $this->pluginPrefix . '/admin/Channels/update',
            'path' => '/Channels/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('wallet', '钱包', [
            'api'    => $this->pluginPrefix . '/admin/UserWallet/index',
            'path' => '/UserWallet/index',
            'aliasParams' => [
                'uid'
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('keywords', 'input', '搜索', [
            'placeholder' => '姓名、手机号搜索'
        ]);
        $builder->addScreen('category_id', 'select', '类目', [
            'options' => MassageUserChannelsCategory::getOptions($request->saas_appid)
        ]);
        $builder->addScreen('state', 'select', '状态', [
            'options' => State::getOptions()
        ]);
        $builder->addScreen('examine', 'select', '审核', [
            'options' => Examine::getOptions()
        ]);
        $builder->addScreen('regions', 'input', '地区', [
            'placeholder' => '地区模糊搜索'
        ]);
        $builder->addScreen('is_empty_code', 'select', '入驻', [
            'options' => [
                ['label' => '已入驻', 'value' => 'not_empty_code'],
                ['label' => '空码', 'value' => 'empty_code'],
            ]
        ]);
        $builder->addScreen('expire_time', 'select', '到期时间', [
            'options' => [
                ['label' => '永久', 'value' => 'permanent'],
                ['label' => '已到期', 'value' => 'expired'],
                ['label' => '即将到期(一月)', 'value' => 'expire_month'],
                ['label' => '即将到期(一周)', 'value' => 'expire_week'],
                ['label' => '即将到期(三天)', 'value' => 'expire_day'],
                ['label' => '即将到期', 'value' => 'will_expire'],
                ['label' => '未到期', 'value' => 'not_expire'],
            ]
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('uid', 'UID', [
                'width' => 120,
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120,
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('salesman_name', '业务员', [
                'width' => 140
            ])
            ->addColumn('title', '名称', [
                'width' => 140
            ])
            ->addColumn('category_name', '类目', [
                'width' => 140
            ])
            ->addColumn('commission_text', '分成比例', [
                'width' => 140
            ])
            ->addColumn('platform_commission_text', '平台承担比例', [
                'width' => 140
            ])
            ->addColumn('province', '省', [
                'width' => 120,
            ])
            ->addColumn('city', '市', [
                'width' => 120,
            ])
            ->addColumn('area', '区', [
                'width' => 120,
            ])
            ->addColumn('street', '街道', [
                'width' => 120,
            ])
            ->addColumn('address_detail', '详细地址', [
                'minWidth' => 120,
            ])
            ->addColumn('remark', '备注', [
                'minWidth' => 120,
            ])
            ->addColumn('expire_time', '到期时间', [
                'width' => 160
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Channels/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ])
            ->addColumnEle('examine', '审核', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '状态备注', [
                'minWidth' => 120,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['a.saas_appid', '=', $request->saas_appid]
        ];
        $keywords = $request->get('keywords');
        if ($keywords) {
            $where[] = ['a.name|a.mobile', 'like', "%{$keywords}%"];
        }
        $regions = $request->get('regions');
        if ($regions) {
            $where[] = ['a.province|a.city|a.area', 'like', "%{$regions}%"];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['a.state', '=', $state];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['a.examine', '=', $examine];
        }
        $category_id = $request->get('category_id');
        if ($category_id) {
            $where[] = ['a.category_id', '=', $category_id];
        }
        $is_empty_code = $request->get('is_empty_code','not_empty_code');
        if ($is_empty_code=='empty_code') {
            $where[] = ['a.uid', '=', NULL];
        }else{
            $where[] = ['a.uid', 'NOT NULL', NULL];
        }
        $expire_time = $request->get('expire_time');
        if ($expire_time) {
            switch ($expire_time) {
                case 'permanent':
                    $where[] = ['a.expire_time', '=', NULL];
                    break;
                case 'expired':
                    $where[] = ['a.expire_time', '<', date('Y-m-d H:i:s')];
                    break;
                case 'expire_month':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 month'))]];
                    break;
                case 'expire_week':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 week'))]];
                    break;
                case 'expire_day':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+3 day'))]];
                    break;
                case 'will_expire':
                    $where[] = ['a.expire_time', 'between', [date('Y-m-d H:i:s'), date('Y-m-d H:i:s', strtotime('+1 month'))]];
                    break;
                case 'not_expire':
                    $where[] = ['a.expire_time', '>', date('Y-m-d H:i:s')];
                    break;
            }
        }
        $data = MassageUserChannels::where($where)
            ->alias('a')
            ->join('massage_user u', 'u.id=a.uid', 'LEFT')
            ->join('massage_user_channels_category c', 'c.id=a.category_id', 'LEFT')
            ->join('massage_user s', 's.id=a.salesman_uid', 'LEFT')
            ->order('a.create_time desc')
            ->field('a.*,u.nickname,u.headimg,c.title as category_name,s.nickname as salesman_name')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->uid) {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
                if ($item->salesman_uid) {
                    $item->salesman_name = "({$item->salesman_uid})".base64_decode($item->salesman_name);
                }
                if ($item->expire_time) {
                    if ($item->expire_time < date('Y-m-d H:i:s')) {
                        $item->expire_time = '已到期';
                    }
                } else {
                    $item->expire_time = '永久';
                }
                $item->commission_text = $item->commission > 0 ? $item->commission . '%' : '系统设置';
                $item->platform_commission_text = $item->platform_commission > 0 ? $item->platform_commission . '%' : '系统设置';
            });
        return $this->successRes($data);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageUserChannels = MassageUserChannels::where($where)->find();
        if (!$MassageUserChannels) {
            return $this->fail('数据不存在');
        }
        $MassageUserChannels->state = $request->post('value');
        if ($MassageUserChannels->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $MassageUserChannels = MassageUserChannels::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageUserChannels) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            Db::startTrans();
            try {
                $MassageUserChannels->title = $D['title'];
                $MassageUserChannels->mobile = $D['mobile'];
                $MassageUserChannels->state = $D['state'];
                if ($MassageUserChannels->state == State::NO['value'] && isset($D['message'])) {
                    $MassageUserChannels->message = $D['message'];
                } else {
                    $MassageUserChannels->message = '';
                }
                if (!empty($D['expire_time'])) {
                    $MassageUserChannels->expire_time = $D['expire_time'] . ' 23:59:59';
                    if ($D['expire_time'] < date('Y-m-d H:i:s')) {
                        $MassageUserChannels->state = State::NO['value'];
                    }
                }
                if (empty($D['commission'])) {
                    $MassageUserChannels->commission = null;
                } else {
                    $MassageUserChannels->commission = $D['commission'];
                }
                if (empty($D['platform_commission'])) {
                    $MassageUserChannels->platform_commission = null;
                } else {
                    $MassageUserChannels->platform_commission = $D['platform_commission'];
                }
                $MassageUserChannels->save();
                Db::commit();
                return $this->success('审核成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '名称', '', [
            'col'           => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col'           => 12,
        ]);
        $builder->addComponent('province', 'info', '省', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('city', 'info', '市', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('area', 'info', '区', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('remark', 'info', '备注', '', [
            'col'           => 24,
        ]);
        $builder->addRow('state', 'radio', '状态', State::YES['value'], [
            'col' => 12,
            'options' => State::getOptions(),
            'control' => [
                [
                    'value' => State::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '状态备注')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '状态备注',
                            ])
                    ],
                ],
            ]
        ]);
        $builder->addRow('expire_time', 'date', '到期时间', '', [
            'col' => 12,
            'props' => [
                'type' => 'date',
                'format' => 'YYYY-MM-DD',
                'value-format' => 'YYYY-MM-DD',
                'clearable' => true,
                'placeholder' => '请选择时间',
            ]
        ]);
        $builder->addRow('commission', 'number', '独立分成比例', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则渠道商佣金为订单金额的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $builder->addRow('platform_commission', 'number', '独立平台承担比例', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则平台承担渠道商佣金的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $MassageUserChannels->expire_time = $MassageUserChannels->expire_time ? date('Y-m-d', strtotime($MassageUserChannels->expire_time)) : '';
        $data = $builder->setData($MassageUserChannels)->create();
        return $this->successRes($data);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageUserChannels = MassageUserChannels::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageUserChannels) {
            return $this->fail('数据不存在');
        }
        $MassageUser = MassageUser::alias('u')->where(['u.id' => $MassageUserChannels->uid])
            ->join('MassageUserWechat uw', 'uw.uid=u.id', 'left')
            ->field('u.id,u.nickname,u.realname,u.mobile,uw.openid')
            ->find();
        if (!$MassageUser) {
            return $this->fail('用户不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageUserChannels->examine = $D['examine'];
            Db::startTrans();
            try {
                if (!in_array($MassageUserChannels->examine, [Examine::YES['value'], Examine::NO['value']])) {
                    throw new \Exception('请选择审核状态');
                }
                $notice = new Notice();
                $notice->addUSER($MassageUser->mobile, $MassageUser->openid);
                $notice->saas_appid = $MassageUserChannels->saas_appid;
                $notice->type = NoticeType::EXAMINE['value'];
                $notice->role = ['TECHNICIAN'];
                if ($MassageUserChannels->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $notice->setData([
                        'type' => '渠道商申请',
                        'state' => '已驳回',
                        'result' => $D['message'],
                        'trade' => $MassageUserChannels->id,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserChannels->message = $D['message'];
                    $MassageUserChannels->state=State::NO['value'];
                } else {
                    $notice->setData([
                        'type' => '渠道商申请',
                        'state' => '已通过',
                        'result' => '恭喜您，您的渠道商入驻申请已通过',
                        'trade' => $MassageUserChannels->id,
                        'time' => date('Y-m-d H:i:s')
                    ]);
                    $MassageUserChannels->message = '通过';
                    $MassageUserChannels->state=State::YES['value'];
                }
                $MassageUserChannels->save();
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
            $notice->send();
            return $this->success('审核成功');
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('title', 'info', '名称', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('mobile', 'info', '手机号', '', [
            'col'           => 18,
        ]);
        $builder->addComponent('province', 'info', '省', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('city', 'info', '市', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('area', 'info', '区', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('审核');
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 12,
            'options' => Examine::getOptions(),
            'control' => [
                [
                    'value' => Examine::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '驳回理由')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '请输入驳回理由',
                            ])
                    ],
                ],
            ]
        ]);
        $builder->addRow('expire_time', 'date', '到期时间', '', [
            'col' => 12,
            'props' => [
                'type' => 'date',
                'format' => 'YYYY-MM-DD',
                'value-format' => 'YYYY-MM-DD',
                'clearable' => true,
                'placeholder' => '请选择时间',
            ]
        ]);
        $builder->addRow('commission', 'number', '独立分成比例', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则渠道商佣金为订单金额的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $builder->addRow('platform_commission', 'number', '独立平台承担佣金', '', [
            'col' => 12,
            'props' => [
                'prompt' => [
                    'text' => '佣金比例为0-100之间的整数，如设置为10，则平台承担渠道商佣金的10%，0或不填：使用系统设置',
                ],
                'props' => [
                    'min' => 0,
                    'max' => 100,
                    'precision' => 0,
                ]
            ]
        ]);
        $data = $builder->setData($MassageUserChannels)->create();
        return $this->successRes($data);
    }
    public function billGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('uid', 'input', 'UID', [
            'placeholder' => 'UID搜索'
        ]);
        $builder->addScreen('mobile', 'input', '手机号', [
            'placeholder' => '手机号搜索'
        ]);
        $builder->addColumn('id', 'ID', [
            'width' => 90
        ]);
        $builder->addColumn('uid', 'UID', [
            'width' => 90
        ])
            ->addColumn('mobile', '手机号', [
                'width' => 120
            ])
            ->addColumnEle('headimg', '头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '昵称', [
                'width' => 120
            ])
            ->addColumn('money', '变动金额', [
                'width' => 120
            ])
            ->addColumn('old_money', '变动前', [
                'width' => 120
            ])
            ->addColumn('new_money', '变动后', [
                'width' => 120
            ])
            ->addColumnEle('action', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => MoneyAction::dictOptions(),
                    'style' => MoneyAction::dictOptions('style'),
                ],
            ])
            ->addColumn('remarks', '备注')
            ->addColumn('create_time', '时间', [
                'width' => 160
            ]);
        return $this->successRes($builder->create());
    }
    public function bill(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [];
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['log.uid', '=', $uid];
        }
        $where[] = ['log.saas_appid', '=', $request->saas_appid];
        $data = MassageUserChannelsBill::where($where)
            ->alias('log')
            ->join('massage_user u', 'log.uid=u.id', 'LEFT')
            ->order('log.id desc')
            ->field('log.*,u.mobile,u.nickname,u.headimg')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            });
        return $this->successRes($data);
    }
}
